package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author SunSun
 * @date 2021/10/30
 */

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Long userId, Long friendId) {
        Criteria criteria=Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Query query=Query.query(criteria);
        if(!mongoTemplate.exists(query,Friend.class)){
            Friend friend1=new Friend();
            friend1.setFriendId(friendId);
            friend1.setUserId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

        Criteria criteria1=Criteria.where("userId").is(friendId).and("friendId").is(userId);
        Query query1=Query.query(criteria1);
        if(!mongoTemplate.exists(query1,Friend.class)){
            Friend friend2=new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public List<Friend> findByUserID(Long userId, Integer page, Integer pagesize) {
        Criteria criteria=Criteria.where("userId").is(userId);
        Query query=Query.query(criteria).skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        return mongoTemplate.find(query,Friend.class);

    }
}
